package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiCar;
import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_member_partner_task;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiT_order_detail;
import cn.com.api.entity.ApiT_user_cash_records;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_advert;
import cn.com.api.entity.ApiU_bonus;
import cn.com.api.entity.ApiU_coupon;
import cn.com.api.entity.ApiU_coupon_detail;
import cn.com.api.entity.ApiU_message;
import cn.com.api.mapper.ApiCarMapper;
import cn.com.api.mapper.ApiGoodsMapper;
import cn.com.api.mapper.ApiJuanMapper;
import cn.com.api.mapper.ApiT_goods_topicMapper;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_member_partner_taskMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_order_detailMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_advertMapper;
import cn.com.api.mapper.ApiU_bonusMapper;
import cn.com.api.mapper.ApiU_couponMapper;
import cn.com.api.mapper.ApiU_coupon_detailMapper;
import cn.com.api.mapper.ApiU_messageMapper;
import cn.com.api.mapper.ApiU_user_labelMapper;
import cn.com.api.service.ApiT_orderService;
import cn.com.api.service.impl.base.T_orderServiceImplBase;
import cn.com.uthink.util.DateTimeUtil;
import cn.com.util.ArithUtil;
import cn.com.util.CipherUtil;
import cn.com.util.DateUtil;
import cn.com.util.PageInfo;
import cn.com.util.Random;
import cn.com.util.Util;
import cn.com.util.Utils;

/**
 * 
 **/
@Service
public class ApiT_orderServiceImpl extends T_orderServiceImplBase implements ApiT_orderService {
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	@Autowired
	private ApiT_order_detailMapper apiT_order_detailMapper;
	@Autowired
	private ApiGoodsMapper apiGoodsMapper;
	@Autowired
	private ApiT_goods_topicMapper goods_topicMapper;
	@Autowired
	private ApiT_productsMapper productsMapper;
	@Autowired
	private ApiT_memberMapper apiT_memberMapper;
	@Autowired
	private ApiU_advertMapper apiU_advertMapper;
	@Autowired
	private ApiU_bonusMapper apiU_bonusMapper;
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiCarMapper apiCarMapper;
	@Autowired
	private ApiU_couponMapper apiU_coupon_Mapper;
	@Autowired
	private ApiU_coupon_detailMapper apiU_coupon_detailMapper;
	@Autowired
	private ApiU_messageMapper apiU_messageMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiU_user_labelMapper apiU_user_labelMapper;
	@Autowired
	private ApiT_member_partner_taskMapper apiT_member_partner_taskMapper;
	@Autowired
	private ApiJuanMapper apiJuanMapper;

	// 新增对象后返回记录ID
	public int T_orderInsertion(ApiT_order t_order) {
		return this.apiT_orderMapper.T_orderInsertion(t_order);
	}

	public List<ApiT_order> findOrderByMap(Map map) {
		return this.apiT_orderMapper.findOrderByMap(map);
	}

	@Override
	public List<ApiT_order> getOrdersByUserId(String userId, String status, int from, int to) {
		return apiT_orderMapper.getOrdersByUserId(userId, status, from, to);
	}

	public List<ApiT_order> getUserOrders(String userId, String status, PageInfo page) {
		return apiT_orderMapper.getOrdersListPage(userId, status, page);
	}

	@Override
	public boolean checkProductStatus(String productId, String topicId) {
		// state 0 活动结束 1 进行中
		boolean flag = false;
		String goodId = apiGoodsMapper.getGoodIdByProductId(productId);
		// goods_topicMapper.getInActiveGoods(goodId,topicId);
		if (!Util.isNull(goods_topicMapper.getInActiveGoods(goodId, topicId))) {
			flag = true;// 有
		}
		return flag;
	}

	@Override
	public void cancelOrder(Map<String, Object> map) {

		apiT_orderMapper.cancelOrder(map);
	}

	@Override
	public ApiT_order getOrderByOrderNum(String orderNum) {
		// TODO Auto-generated method stub
		return apiT_orderMapper.getOrderByOrderNum(orderNum);
	}

	@Override
	public List<Map<String, Object>> getRelationByProduct(List<String> productIds, String userId, String currentDay,
			String currentHour) {
		// TODO Auto-generated method stub
		return apiT_orderMapper.getRelationByProduct(productIds, userId, currentDay, currentHour);
	}

	@Override
	public boolean checkProductStore(String productId, String count) {
		boolean bol = false;
		String store = productsMapper.searStoreByProId(productId);
		if (Integer.parseInt(count) > Integer.parseInt(store)) {
			bol = true;
		}
		return bol;
	}

	@Override
	public void updateOrderEnable(String id) {
		apiT_orderMapper.updateOrderEnable(id);
	}

	@Override
	public List<Map<String, Object>> getRelationByProduct(List<String> productIds, String userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ApiT_order getorderInfoByadvertid(String advertid) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("target_id", advertid);
		map.put("ordertype", "5"); // 广告订单
		ApiT_order_detail apiT_order_detail = apiT_order_detailMapper.findOrderDetailsByMap(map);
		ApiT_order apiT_order = apiT_orderMapper.findT_orderByOrderNum(apiT_order_detail.getDid());
		return apiT_order;
	}

	@Override
	public void updateOrderDDstatusByOrderNum(String orderNum, String status) {
		// TODO Auto-generated method stub
		apiT_orderMapper.updateDDStatusBySerialFlagNo(orderNum, status);
	}

	@Override
	public void updateRemindShipmentByOrderNum(String orderNum, String time) {
		apiT_orderMapper.updateRemindShipmentByOrderNum(orderNum, time);
	}

	@Override
	public List<Map<String, String>> selectByOrListPage(Map<String, Object> map, PageInfo pageInfo) throws Exception {
		// TODO Auto-generated method stub
		return apiT_orderMapper.selectByOrListPage(map, pageInfo);
	}

	// 我的订单
	public List<ApiT_order> selectMyOrderListPage(Map<String, Object> map, PageInfo pageInfo) throws Exception {
		return apiT_orderMapper.selectMyOrderListPage(map, pageInfo);
	}

	/*
	 * @Override public List<Map<String, Object>>
	 * selectOrderDianPing(Map<String, Object> map, PageInfo pageInfo) { // TODO
	 * Auto-generated method stub return
	 * apiT_orderMapper.selectOrderDianPingListPage(map, pageInfo); }
	 */

	@Override
	public List<Map<String, Object>> selectBackOrder(Map<String, Object> map, PageInfo pageInfo) {
		return apiT_orderMapper.selectBackOrderListPage(map, pageInfo);
	}

	@Override
	public void updateSendStatus(Map<String, Object> map) {
		apiT_orderMapper.updateSendStatus(map);
	}

	@Override
	public int findT_orderCountByTargetId(Map<String, String> params) {
		// TODO Auto-generated method stub
		return apiT_orderMapper.findT_orderCountByTargetId(params);
	}

	/*
	 * 根据广告订单创建订单
	 */
	@Transactional
	public ApiT_order createadvertorder(Integer advertid, ApiT_member apiT_member, ApiU_advert advert)
			throws Exception {
		ApiT_order t_order = new ApiT_order();
		t_order.setTitles("");
		t_order.setShop_id("");
		t_order.setUser_id(apiT_member.getC_id() + "");
		t_order.setPeisong("");// 1 物流 2 自提
		if (apiT_member != null) {
			t_order.setName(apiT_member.getC_cname());// 根据userId获取
			t_order.setTel(apiT_member.getC_tel());// 根据userId获取
			t_order.setMobile("");// 根据userId获取
			t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
			t_order.setZip(apiT_member.getC_zip());// 根据userId获取
		}
		t_order.setAddress("");
		t_order.setDtime("");// 送达时间 //待定
		t_order.setBz("");

		t_order.setMoney(advert.getTotal_amount());
		t_order.setAppuser("");
		t_order.setAppdate(DateUtil.nowTimeToString());
		t_order.setRip("");
		t_order.setTitles(advert.getAdv_name());
		t_order.setEnable(1);// 未完成订单
		t_order.setZi_status(0);// 未支付
		t_order.setDd_status(1);// 未支付
		t_order.setOrdertype(5);// 5-广告订单
		String dingDanNo = Utils.getDingDanNo("");
		t_order.setOrdernum(dingDanNo);
		t_order.setSerialflagno(dingDanNo);
		apiT_orderMapper.T_orderInsertion(t_order);

		ApiT_order_detail order_detail = new ApiT_order_detail();
		order_detail.setDid(dingDanNo);
		order_detail.setMoney(advert.getTotal_amount());
		order_detail.setNum(1);
		order_detail.setTarget_id(advertid + "");
		apiT_order_detailMapper.T_order_detailInsertion(order_detail);
		return t_order;
	}

	// 余额支付
	@Transactional
	public Map<String, Object> usermoneypay(String serialflagno, String password, Integer user_id, BigDecimal amount)
			throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		// 根据订单号查询订单信息
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		params.put("serialflagno", serialflagno);
		if (apiT_member.getPay_pwd() != null && !"".equals(apiT_member.getPay_pwd())) {
			if (!CipherUtil.generatePassword(password).equals(apiT_member.getPay_pwd())) {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "支付密码不正确");
			} else {
				if (amount.compareTo(apiT_member.getC_money()) > 0) {// 余额不足
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "余额不足");
				} else {
					// 用户金额变动明细表中插信息
					List<ApiT_order> list = apiT_orderMapper.findOrderByMap(params);
					if (list == null || list.size() == 0 || list.get(0).getZi_status() == 1) {
						map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
						map.put(Utils.MESSAGE, "订单不存在或已支付");
					} else {
						ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
						apiT_user_cash_records.setUser_id(user_id + "");
						ApiU_message message = new ApiU_message();
						String nowTimeToString = DateUtil.nowTimeToString();
						for (ApiT_order apiT_order : list) {
							apiT_order.setZi_status(1);// 已支付
							apiT_order.setDd_status(2);// 已付款
							apiT_order.setZf_type("0");
							apiT_order.setPaytime(nowTimeToString);
							apiT_orderMapper.updateT_order(apiT_order);

							// 广告订单
							if (apiT_order.getOrdertype() == 5) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 广告改为已支付状态
								ApiU_advert advert = apiU_advertMapper
										.findU_advertById(Integer.valueOf(apiT_order_detail.getTarget_id()));
								advert.setIs_pay(1);
								apiU_advertMapper.updateU_advert(advert);
								// 如果有红包，更新红包的支付状态
								if (advert.getBonus_id() != null && !"".equals(advert.getBonus_id())) {
									ApiU_bonus apiU_bonus = apiU_bonusMapper
											.findU_bonusById(Integer.valueOf(advert.getBonus_id()));
									apiU_bonus.setIs_pay(1);
									apiU_bonusMapper.updateU_bonus(apiU_bonus);
								}
								apiT_user_cash_records.setRemark("购买广告");
								apiT_user_cash_records.setCate_type(5);
								message.setTitle("广告购买成功");
								message.setContent("您购买了广告");
							} else if (apiT_order.getOrdertype() == 6) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 普通红包改为已支付状态
								ApiU_bonus apiU_bonus = apiU_bonusMapper
										.findU_bonusById(Integer.valueOf(apiT_order_detail.getTarget_id()));
								apiU_bonus.setIs_pay(1);
								apiU_bonusMapper.updateU_bonus(apiU_bonus);
								apiT_user_cash_records.setRemark("发红包");
								apiT_user_cash_records.setCate_type(6);
								message.setContent("您发了一个红包");
							} else if (apiT_order.getOrdertype() == 0) {
								String allMoney = apiT_orderMapper.getAllPayMoneyBySerialFlagNo(serialflagno);
								if (Util.getBigDecimal(allMoney).compareTo(amount) == 0) {
									// 购物订单
									apiT_orderMapper.updateDDStatusBySerialFlagNo(serialflagno, "2");// 已付款
									// 扣减库存
									List<ApiT_order_detail> orderDetailList = apiT_order_detailMapper
											.getOrderDetailBySerialFlagNo(serialflagno);
									for (ApiT_order_detail orderDetailObj : orderDetailList) {
										String store = apiT_productsMapper
												.searStoreByProId(orderDetailObj.getProduct_id().toString());
										long num = orderDetailObj.getNum();
										int left = (int) (Integer.parseInt(store) - num);
										apiT_productsMapper.updStoreByProId(orderDetailObj.getProduct_id(), left);
									}
									// 修改购物车
									String cardIds = "";
									List<String> cardIdList = apiT_orderMapper.getCardIdsBySerialFlagNo(serialflagno);
									for (String string : cardIdList) {
										cardIds += string + ",";
									}
									String[] carIdArr = cardIds.split(",");
									for (int i = 0; i < carIdArr.length; i++) {
										apiCarMapper.updateCarByCarId(carIdArr[i], "1");// 已支付
									}
								} else {
									/** start huangshi001 update */
									// 金额校验后期统一处理，其他地方暂不修改
									map.put(Utils.MESSAGE, "支付金额不正确");
									map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
									throw new Exception("支付金额不正确");
									/** end huangshi001 update */
								}
								/** start huangshi001 update */
								apiT_user_cash_records.setRemark("购买了商品");
								apiT_user_cash_records.setCate_type(0);
								message.setTitle("您的宝贝购买成功");
								message.setContent("您在首媒中国-特卖会的订单付款成功，宝贝已整装待发，请耐心等待哦");
							} else if (apiT_order.getOrdertype() == 8) {
								// 暂无逻辑,新发现订单
								// 如果需要修改库存,则需要增加字段
							} else if (apiT_order.getOrdertype() == 9) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 优惠券押金订单,订单为一个，优惠券ID可能为多个
								String target_id = apiT_order_detail.getTarget_id();
								String[] target_id_list = target_id.split(",");
								for (String coupon_id : target_id_list) {
									ApiU_coupon apiU_coupon = apiU_coupon_Mapper
											.findU_couponById(Integer.valueOf(coupon_id));
									apiU_coupon.setDeposit_status(1);
									apiU_coupon_Mapper.updateU_coupon(apiU_coupon);
								}
								apiT_user_cash_records.setCate_type(4);
								apiT_user_cash_records.setRemark("在线交易");
							} else if (apiT_order.getOrdertype() == 10) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 优惠券支付订单
								String target_id = apiT_order_detail.getTarget_id();
								ApiU_coupon_detail apiU_coupon_detail = apiU_coupon_detailMapper
										.findU_coupon_detailById(Integer.valueOf(target_id));
								apiU_coupon_detail.setUse_time(nowTimeToString);
								apiU_coupon_detail.setStatus(1);
								apiU_coupon_detailMapper.U_coupon_detailInsertion(apiU_coupon_detail);
								apiT_user_cash_records.setCate_type(4);
								apiT_user_cash_records.setRemark("在线交易");
							} else if (apiT_order.getOrdertype() == 11) {// 转账
								String touserId = apiT_order.getExt_1();// 转给某用户的
								ApiT_member toMember = apiT_memberMapper.findT_memberById(Integer.valueOf(touserId));
								String createType = apiT_order.getExt_2();// 是否需要对方接受转账
								if ("0".equals(createType)) { // 0-扫码支付（转账），不需要对方确认
									apiT_user_cash_records.setIs_receive(1);// 已领取

									// 已领取则增加一条已领取的记录
									ApiT_user_cash_records receiverecords = new ApiT_user_cash_records();
									receiverecords.setUser_id(touserId);
									receiverecords.setConn_id(apiT_order.getUser_id());
									receiverecords.setCate_type(7);
									receiverecords.setRemark(apiT_order.getC_nick() + " 转账给我");
									receiverecords.setProcess_type(0);
									receiverecords.setIs_receive(1);
									receiverecords.setCreate_time(nowTimeToString);
									receiverecords.setMoney(amount);
									receiverecords.setOrder_id(serialflagno);
									receiverecords.setPay_type(0);
									receiverecords.setPay_type_desc("0");
									apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(receiverecords);
									// 改变结束方的金额
									toMember.setC_money(toMember.getC_money().add(amount));
									apiT_memberMapper.updateT_member(toMember);

									ApiU_message receivemessage = new ApiU_message();
									receivemessage.setContent(apiT_order.getC_nick() + "给您转账了" + amount + "元");
									receivemessage.setTitle("转账");
									receivemessage.setType(10);
									receivemessage.setAdd_time(nowTimeToString);
									receivemessage.setConn_id(list.get(0).getRid());
									receivemessage.setUser_id(toMember.getC_id() + "");
									receivemessage.setIs_read(0);
									apiU_messageMapper.insertU_message(receivemessage);

								} else if ("1".equals(createType)) {// 1-表示普通的转账，需要对方确认，
									apiT_user_cash_records.setIs_receive(0);// 未领取
								}
								apiT_user_cash_records.setConn_id(touserId);
								apiT_user_cash_records.setCate_type(7);
								apiT_user_cash_records.setRemark("转账给 " + toMember.getC_nick());
							}
							/** end huangshi001 update */
						}

						if (list.get(0).getOrdertype() == 11) {// 转账
							message.setContent("您转出了" + amount + "元");
							message.setTitle("转账");
							message.setType(10);
						} else {// 在线交易
							message.setTitle("在线交易");
							message.setType(7);
						}

						apiT_user_cash_records.setCreate_time(nowTimeToString);
						apiT_user_cash_records.setMoney(amount);
						apiT_user_cash_records.setOrder_id(serialflagno);
						apiT_user_cash_records.setPay_type(0);
						apiT_user_cash_records.setPay_type_desc("0");
						apiT_user_cash_records.setProcess_type(1);
						apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);
						// 余额支付,更新用户的金额
						apiT_member.setC_money(apiT_member.getC_money().subtract(amount));
						apiT_memberMapper.updateT_member(apiT_member);

						message.setAdd_time(nowTimeToString);
						message.setConn_id(list.get(0).getRid());
						message.setUser_id(user_id + "");
						message.setIs_read(0);
						apiU_messageMapper.U_messageInsertion(message);
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "支付成功");
					}
				}
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "用户未设置支付密码");
		}
		return map;
	}

	@Transactional
	public Map<String, Object> create_order(String userId, String carIds, String pwd, String payType, String address,
			String peiSong, String memo, String sendfee, String rIp, String isQuan, String quanId, String receiptTitle,
			String receiptDesc, String receiptRemark) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		String payStr = "";
		if (payType.equals("0")) {
			pwd = CipherUtil.generatePassword(pwd);
			if (Util.isNull(apiTmemberMapper.checkPayPass(userId, pwd))) {
				map.put(Utils.RESULT, "0033");
				map.put(Utils.MESSAGE, "密码错误");
				payStr = "error";
			}
		}
		String products_ids = "";
		// String topic_ids = "";
		String nums = "";
		List<String> cardIdList = new ArrayList<>();
		String cardIdArr[] = carIds.split(",");
		for (int i = 0; i < cardIdArr.length; i++) {
			cardIdList.add(cardIdArr[i]);
		}
		List<ApiCar> carList = apiCarMapper.getCarInfoByCarIds(cardIdList);
		for (ApiCar apiCar : carList) {
			products_ids += apiCar.getProduct_id() + ",";
			// topic_ids += apiCar.getTopic_id() + ",";
			nums += apiCar.getCount() + ",";
		}
		// int finishNum = 0;
		int overNum = 0;
		List<String> productIdList = new ArrayList<>();
		String productIdArr[] = products_ids.split(",");
		// String topicIdArr[] = topic_ids.split(",");
		String numsArr[] = nums.split(",");

		// List<Map<String,Object>> errorList=new ArrayList<>();
		// Map<String,Object> errorMap=new HashMap<>();
		for (int i = 0; i < productIdArr.length; i++) {
			// errorMap=new HashMap<>();
			// if
			// (!apiT_orderService.checkProductStatus(productIdArr[i],topicIdArr[i]))
			// {
			// //errorMap.put("id", productIdI);
			// errorMap.put("name",productsService.getProductNameProductId(productIdI));
			// finishNum++;
			// //errorList.add(errorMap);
			// }
			if (checkProductStore(productIdArr[i], numsArr[i])) {
				overNum++;
			}
			productIdList.add(productIdArr[i]);
		}

		if (overNum > 0) {
			map.put(Utils.RESULT, "0073");
			map.put(Utils.MESSAGE, "存在库存不足抢购商品");
		} else {
			String currDate = DateTimeUtil.getTimeByStyle("yyyy-MM-dd");
			String currHour = DateTimeUtil.getTimeByStyle("HH");
			List<Map<String, Object>> relationList = getRelationByProduct(productIdList, userId, currDate, currHour);
			// String memberId=
			// relationList.get(0).get("USER_ID").toString().split("_")[0];
			String orderNo = "";
			if (!Util.isNull(relationList)) {
				orderNo = Utils.getDingDanNo("");
				for (int i = 0; i < relationList.size(); i++) {
					String memberId = relationList.get(i).get("user_id").toString();

					ApiTmember member = apiTmemberMapper.findMemberByCid(Integer.parseInt(userId));
					if (!Util.isNull(member)) {
						// 兴趣爱好是否设置
						Integer intCount = apiU_user_labelMapper.checkUserLabel(userId, 1);
						member.setIs_Interest(intCount);
						// 专业领域是否设置
						Integer intArea = apiU_user_labelMapper.checkUserLabel(userId, 3);
						member.setIs_Area(intArea);
						// 核伙人等级
						List<ApiT_member_partner_task> task_list = this.apiT_member_partner_taskMapper
								.getMemberTaskLevel(userId);
						if (task_list.size() > 0) {
							member.setMember_level(task_list.get(0).getMember_level());
						}
					}

					ApiT_order t_order = new ApiT_order();
					t_order.setTitles("");
					t_order.setShop_id(memberId);
					t_order.setUser_id(userId);
					t_order.setPeisong(peiSong);// 1
												// 物流
												// 2
												// 自提
					if (member != null) {
						t_order.setName(member.getCnick());// 根据userId获取
						t_order.setTel(member.getCtel());// 根据userId获取
						t_order.setMobile(member.getCmob());// 根据userId获取
						t_order.setEmail(member.getCmail());// 根据userId获取
						t_order.setZip(member.getCzip());// 根据userId获取
					}
					t_order.setAddress(address);
					t_order.setDtime("");// 送达时间 //待定
					t_order.setTitles("特卖会");

					t_order.setBz(memo);

					double sumGoodsMoney = 0.0;
					String pricesArr[] = relationList.get(i).get("prices").toString().split(",");
					String countsArr[] = relationList.get(i).get("counts").toString().split(",");
					for (int j = 0; j < pricesArr.length; j++) {
						sumGoodsMoney = ArithUtil.add(sumGoodsMoney,
								Double.valueOf(pricesArr[j]) * Double.valueOf(countsArr[j]));
					}

					BigDecimal sendFee = Util.getBigDecimal(sendfee);
					t_order.setSendfee(sendFee);
					t_order.setSumgoodsprice(new BigDecimal(sumGoodsMoney));// 商品的金额
					BigDecimal totalMoney = new BigDecimal(sumGoodsMoney).add(sendFee);
					t_order.setMoney(totalMoney);
					t_order.setAppuser("");
					t_order.setAppdate(DateUtil.nowTimeToString());
					t_order.setRip(rIp);
					t_order.setEnable(0);// 未删除
					// t_order.setZi_status(0);// 未支付
					t_order.setDd_status(1);// 待付款
					t_order.setZf_type(payType);
					if (payType.equals("0")) {
						t_order.setRemainmoney(totalMoney);// 余额 支付方式为0时 插入
					} else {
						t_order.setRemainmoney(BigDecimal.ZERO);// 余额
																// 支付方式为0时
																// 插入
					}
					t_order.setSerial(Random.randomStr());
					String insertOrderNum = "";
					if (i == 0) {
						insertOrderNum = orderNo;
					} else {
						insertOrderNum = Utils.getDingDanNo("");
					}
					t_order.setOrdernum(insertOrderNum);
					t_order.setSerialflagno(orderNo);// 订单一起支付标记首个订单号
					t_order.setOrdertype(0);// 订单类型
					t_order.setPaytime(DateUtil.nowTimeToString());
					t_order.setTakegoodstime("");// 收货时间
					t_order.setCancelreason("");// 订单取消原因
					t_order.setProduct_ids(relationList.get(i).get("productIds").toString());
					t_order.setCar_ids(relationList.get(i).get("carId").toString());
					t_order.setIs_quan(Integer.parseInt(isQuan));// 是否使用优惠券
																	// 1-使用

					if (Util.isNull(quanId)) {
						quanId = "0";
					}
					t_order.setQuan_id(quanId);
					BigDecimal juanMoney = BigDecimal.ZERO;
					if (quanId != null && !quanId.equals("")) {
						Map<String, Object> juanMap = apiJuanMapper.selectById(quanId);
						if (juanMap != null) {
							juanMoney = Util.getBigDecimal(juanMap.get("CASHED").toString());
						}
					}
					t_order.setPaymoney(new BigDecimal(sumGoodsMoney).subtract(juanMoney).add(sendFee));// 优惠后的金额
					t_order.setSenddate("");// 配送时间
					t_order.setLongitude("");// 收货地址的经度
					t_order.setLatitude("");// 收货地址的纬度
					t_order.setIs_send(0);// 是否配送 //待定
					t_order.setSumpoints(0l);// 订单奖励积分 //待定
					// String orderNo = System.currentTimeMillis()+"";
					t_order.setIs_lunchbox(0);// 是否启用餐盒费：0-未启用 1-启用
					t_order.setLunchbox_price(0);// 餐盒费单价
					t_order.setGoodscount(0);// 订单商品总数量
					t_order.setIs_print(0);// 打印状态 0：未打印；1：已打印
					t_order.setCancle_time("");// 订单取消时间
					t_order.setPrint_time("");// 订单打印时间
					t_order.setOvertime_duty("0");// 超时的责任方。0：未知；1：订单员；2：骑士组长；3：骑士；1,2：订单员和骑士组长；1,3：订单员和骑士；2,3：骑士组长和骑士
					t_order.setWxpaystr("");// 暂时未知

					t_order.setReceipt_title(receiptTitle);
					t_order.setReceipt_desc(receiptDesc);
					t_order.setReceipt_remark(receiptRemark);
					// 插入订单数据
					// apiT_orderService.T_orderInsertion(t_order);

					List<ApiT_order_detail> list = new ArrayList<>();
					ApiT_order_detail order_detail = null;
					String productsArr[] = relationList.get(i).get("productIds").toString().split(",");
					String goodsArr[] = relationList.get(i).get("goodsId").toString().split(",");
					String carIdsArr[] = relationList.get(i).get("carId").toString().split(",");

					for (int j = 0; j < productsArr.length; j++) {
						order_detail = new ApiT_order_detail();
						order_detail.setDid(insertOrderNum + "");
						order_detail.setTarget_id("");
						order_detail.setMoney(Util.getBigDecimal(pricesArr[j]));
						order_detail.setNum(Long.valueOf(countsArr[j]));
						order_detail.setProduct_id(productsArr[j]);
						order_detail.setPoints(0l);// 积分待定
						order_detail.setExt_1(goodsArr[j]);// 商品id
						order_detail.setExt_2(carIdsArr[j]);// 购物车id
						list.add(order_detail);
					}
					if (!payStr.equals("error")) {
						T_orderInsertion(t_order);
						apiT_order_detailMapper.batchInsertOrderDetail(list);
					}
				}
				if (!payStr.equals("error")) {
					apiCarMapper.updateCardStatusByList(cardIdList, "2");
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "添加成功！");
					map.put("orderNum", orderNo);
				}
			} else {
				map.put(Utils.RESULT, "1234");
				map.put(Utils.MESSAGE, "购物车信息不正确！");
				map.put("orderNum", orderNo);
			}
		}
		return map;
	}
}
